package Server3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;
    private Server(){
        try{
            serverSocket=new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void start(){
        try {
            while (true){
                System.out.println("等待链接");
                Socket socket=serverSocket.accept();
                System.out.println("链接成功");
                //启动线程
                ClientHandler handler=new ClientHandler(socket);

                Thread h=new Thread(handler);
                h.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket=socket;
            this.host=socket.getInetAddress().getHostAddress();//获取id，就是ip地址
        }
        public void run(){
            try {
                InputStream is=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is,"UTF-8");
                BufferedReader br=new BufferedReader(isr);

                OutputStream os=socket.getOutputStream();
                OutputStreamWriter ow=new OutputStreamWriter(os,"UTF-8");
                BufferedWriter bw=new BufferedWriter(ow);
                PrintWriter pw=new PrintWriter(bw,true);


                String message;
                while ((message= br.readLine())!=null){
                    System.out.println("客户端"+host+"发来消息："+message);
                    pw.println("客户端"+host+"发来消息："+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
